//
//  DealerViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 1/31/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DealerViewController.h"
#import "DealerListViewController.h"
#import "ActivityViewManager.h"
#import "ZHDataService.h"
#import "ZHWebService.h"
#import "WDProvince.h"

@interface DealerViewController()
@property (nonatomic, retain) WDProvince *currentProvince;
@property (nonatomic, retain) NSArray *allProvinces;
@property (nonatomic, assign) CGFloat latitude;
@property (nonatomic, assign) CGFloat longitude;

- (void)getUserLocation;
@end

@implementation DealerViewController

@synthesize myTableView;
@synthesize allProvinces;
@synthesize currentProvince;
@synthesize latitude,longitude;

#pragma mark - my own methods
- (void)leftItemClicked
{
    [self getUserLocation];
}

- (void)getUserLocation
{
    //get the current location from gps
	CLLocationManager *locManager = [[CLLocationManager alloc] init];
	[locManager setDelegate:self];
	[locManager setDesiredAccuracy:kCLLocationAccuracyBest]; 
	//Set the filter to 200 meters
	locManager.distanceFilter = 200.f;
	[locManager startUpdatingLocation];
}

#pragma mark - View lifecycle

- (void)dealloc
{
    [currentProvince release];
    [allProvinces release];
    [myTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"经销商";
    myTableView.backgroundColor = [UIColor clearColor];
    [self addNaviBarLeftRefreshItem];
    [self setBackgroundImageViewForTabView];
    [self leftItemClicked];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.myTableView = nil;
}
#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
        return 1;
    else
        return [self.allProvinces count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.textColor = [UIColor cellLeftKeyTextColor];
        cell.textLabel.font = [UIFont getSettingViewTableCellLabelFont];
    }
    if(indexPath.section == 0)
    {
        if(nil != self.currentProvince)
        {
            cell.textLabel.text = self.currentProvince.provinceName;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%d",self.currentProvince.dealerNum];
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.detailTextLabel.hidden = NO;
        }
        else
        {
            cell.textLabel.text = @"请刷新获取当前地址！";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.detailTextLabel.hidden = YES;
        }
    }
    else
    {
        WDProvince *province = [self.allProvinces objectAtIndex:indexPath.row];
        cell.textLabel.text = province.provinceName;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%d",province.dealerNum];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.detailTextLabel.hidden = NO;
    }
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0)
        return @"GPS定位";
    else
        return @"经销商列表";
}
#pragma -
#pragma UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(nil == self.currentProvince && indexPath.section == 0)
        return;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DealerListViewController *dealerListController = [[DealerListViewController alloc] init];
    dealerListController.currentProvince = [self.allProvinces objectAtIndex:indexPath.row];
    dealerListController.latitude = self.latitude;
    dealerListController.longtitude = self.longitude;
    [self.navigationController pushViewController:dealerListController animated:YES];
    [dealerListController release];
}


#pragma mark - CLLocationManagerDelegate methods

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation
{
	//Request for new annotations
    [manager stopUpdatingLocation];
    manager.delegate = nil;
    [manager release];
    manager = nil;
    
    CLLocationCoordinate2D loc = [newLocation coordinate];
    self.latitude = loc.latitude;
    self.longitude = loc.longitude;
	
    CompletionBlock completion = ^(NSData *data){
        NSDictionary *dict = [ZHDataService parseToAllProvincesWithData:data];
        self.allProvinces = [dict objectForKey:@"otherProvinces"];
        self.currentProvince = [dict objectForKey:@"currentProvince"];
        if(self.currentProvince.provinceId == 0)
            self.currentProvince = nil;
        [myTableView reloadData];
    };
    ErrorBlock error = ^(NSString *error){};
    [[ZHWebService sharedService] getAllProvincesWithLat:loc.latitude lon:loc.longitude onCompletion:completion onError:error];
}

- (void)locationManager:(CLLocationManager *)manager
	   didFailWithError:(NSError *)error
{
    [manager stopUpdatingLocation];
    manager.delegate = nil;
    [manager release];
    manager = nil;
    [ActivityViewManager showErrorViewWithMessage:@"无法获取当前地址."];
    self.currentProvince = nil;
    [myTableView reloadData];
}

#pragma mark - MKReverseGeocoderDelegate methods
//- (void)startedReverseGeoderWithLatitude:(double)latitude longitude:(double)longitude{
//	
//    CLLocationCoordinate2D coordinate2D;
//	
//    coordinate2D.longitude = longitude;
//	
//    coordinate2D.latitude = latitude;
//	
//    MKReverseGeocoder *geoCoder = [[[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D] autorelease];
//    
//    geoCoder.delegate = self;
//	
//    [geoCoder start];
//}


//- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
//{
//    NSString *cityName = placemark.locality;
//    NSLog(@"city name:%@",cityName);
//    if(nil == cityName || [cityName isEqualToString:@""])
//    {
//        [ActivityViewManager showErrorViewWithMessage:@"无法获取当前地址."];
//    }
//    self.currentCityName = cityName;
//    [myTableView reloadData];
//}
//
//- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
//{
//    [ActivityViewManager showErrorViewWithMessage:@"无法获取当前地址."];
//    self.currentCityName = nil;
//    [myTableView reloadData];
//}
@end
